<template>
  <div class="users">
    <!-- 面包屑 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>用户管理</el-breadcrumb-item>
      <el-breadcrumb-item>用户列表</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 搜索框 -->
    <!-- query 查询参数 -->
    <el-input placeholder="请输入搜索关键字" v-model="inputValue" class="input-with-select">
      <el-button slot="append" icon="el-icon-search" @click="searchUser"></el-button>
    </el-input>
    <el-button class="addBtn" plain type="success" @click="showAddDialog">添加用户</el-button>
    <!-- 添加对话框 -->
    <el-dialog title="添加用户"
    :visible.sync="dialogVisible"
    @close="closeDialog"
    width="40%">
      <el-form :model="addForm" ref="form" :rules="rules" label-width="100px" status-icon>
        <el-form-item label="用户名" prop="username">
          <el-input v-model="addForm.username" placeholder="请输入用户名"></el-input>
        </el-form-item>
        <el-form-item label="密码" prop="password">
          <el-input v-model="addForm.password" type="password" placeholder="请输入密码"></el-input>
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="addForm.email" placeholder="请输入邮箱" prop="email"></el-input>
        </el-form-item>
        <el-form-item label="手机" prop="id">
          <el-input v-model="addForm.mobile" placeholder="请输入手机号码" prop="mobile"></el-input>
        </el-form-item>
      </el-form>
      <template v-slot:footer>
        <span slot="footer" class="dialog-footer">
          <el-button @click="dialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="addUser">确 定</el-button>
        </span>
      </template>
  </el-dialog>
<!--修改信息框  -->
  <el-dialog title="修改用户"
    :visible.sync="editDialogVisible"
    width="40%">
      <el-form :model="editForm" ref="editForm" :rules="rules" label-width="100px" status-icon>
        <el-form-item label="用户名" prop="username">
          <el-tag type="info">{{editForm.username}}</el-tag>
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="editForm.email" placeholder="请输入邮箱" prop="email"></el-input>
        </el-form-item>
        <el-form-item label="手机" prop="mobile">
          <el-input v-model="editForm.mobile" placeholder="请输入手机号码" prop="mobile"></el-input>
        </el-form-item>
      </el-form>
      <template v-slot:footer>
        <span slot="footer" class="edit-footer">
          <el-button @click="editDialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="editUser" >确 定</el-button>
        </span>
      </template>
</el-dialog>
<!-- 分配角色对话框 -->
  <el-dialog title="分配角色"
    :visible.sync="assignDialogVisible"
    width="40%">
    <el-form :model="assignForm" label-width="80px" status-icon>
      <el-form-item label="用户名">
          <el-tag type="info">{{assignForm.username}}</el-tag>
      </el-form-item>
      <el-form-item label="角色列表">
        <el-select v-model="assignForm.rid" >
           <el-option
            v-for="item in options"
            :key="item.id"
            :label="item.roleName"
            :value="item.id">
           </el-option>
       </el-select>
     </el-form-item>
    </el-form>
    <template v-slot:footer>
        <span slot="footer" class="assign-footer">
          <el-button @click="assignDialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="assginRoles" >分 配</el-button>
        </span>
      </template>
</el-dialog>
<!-- 表格  prop  配置列中的数据, label 标题名-->
 <el-table :data="useList" style="width: 100%">
    <el-table-column prop="username" label="姓名" ></el-table-column>
    <el-table-column prop="email" label="邮箱" ></el-table-column>
    <el-table-column prop="mobile" label="电话" ></el-table-column>
    <el-table-column  label="用户状态">
    <template v-slot:default="obj">
  <!-- <p>{{obj.row.mg_state}}</p>
         遍历时每一项的数据, 其实elementui在定义插槽时, 已经通过作用域插槽传给我们了
         通过作用域插槽可以获取到 row(行, 遍历的一条数据), column(列), $index(下标) 的数据
  -->
  <!-- {row}=obj  =>  obj.row=row -->
  <!-- 修改用户状态 -->
  <el-switch
    @change="changeState(obj.row.id,obj.row.mg_state)"
    v-model="obj.row.mg_state"
    active-color="#13ce66"
    inactive-color="#ff4949"
  ></el-switch>
</template>
    </el-table-column>
      <el-table-column  label="操作">
  <template v-slot:default="obj">
      <el-button type="primary" size="small" plain  icon="el-icon-edit" @click="showEditDialog(obj.row)"></el-button>
      <el-button type="danger"  size="small" plain icon="el-icon-delete" @click="deleteUser(obj.row.id)"></el-button>
      <el-button type="success"  size="small" plain icon="el-icon-check" @click="showAssignDialog(obj.row)">分配角色</el-button>
    </template>
    </el-table-column>
  </el-table>
<!-- 分页 -->
    <!--
      :current-page 当前页
      :page-sizes 可供选择的, 每页条数
      :page-size 每页条数
      layout 功能控件
      @size-change => 表示每页条数变化时, 触发
      @current-change => 当前页变化时, 触发
     -->
   <el-pagination
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
      :current-page="pagenum"
      :page-sizes="[2, 4, 6, 8, 10]"
      :page-size="pagesize"
      layout="total, sizes, prev, pager, next, jumper"
      :total="total">
    </el-pagination>
  </div>
</template>

<script>
export default {
  created () {
    this.getUserList()
  },
  data () {
    return {
      inputValue: '',
      useList: [],
      query: '',
      pagenum: 1,
      pagesize: 2,
      total: 0,
      currentPage4: 4,
      dialogVisible: false,
      addForm: {
        username: '',
        password: '',
        email: '',
        mobile: ''
      },
      editDialogVisible: false,
      editForm: {
        id: '', // id是专门用于修改的
        username: '',
        email: '',
        mobile: ''
      },
      assignForm: {
        id: '',
        username: '',
        rid: ''
      },
      options: [],
      assignDialogVisible: false,
      rules: {
        username: [
          { required: true, message: '请输入用户名', trigger: ['change', 'blur'] },
          { min: 3,
            max: 12,
            message: '用户名必须是3-12位',
            trigger: ['change', 'blur'] }
        ],
        password: [
          { required: true, message: '请输入密码', trigger: ['change', 'blur'] },
          { min: 3,
            max: 8,
            message: '用户名必须是3-8位',
            trigger: ['change', 'blur'] }
        ],
        email: [
          { type: 'email', message: '请输入正确邮箱', trigger: ['change', 'blur'] }
        ],
        mobile: [
          { pattern: /^1\d{10}$/, message: '请输入正确手机号码', trigger: ['change', 'blur'] }
        ]
      }
    }
  },
  methods: {
    // 渲染页面
    async getUserList () {
      const { data, meta } = await this.$axios.get('users', {
        // const { data, meta } = res
        // 配置请求头确保每一次都能够携带令牌
        params: {
          query: this.query,
          pagenum: this.pagenum,
          pagesize: this.pagesize
        }
      })
      if (meta.status === 200) {
        this.total = data.total
        this.pagenum = data.pagenum
        this.useList = data.users
      } else {
        this.$massage.error(meta.msg)
      }
    },
    // 分页器--切换每页的条数
    handleSizeChange (val) {
      //  pagesize每页条数
      this.pagesize = val
      this.pagenum = 1
      this.getUserList()
      // console.log(`每页 ${val} 条`)
    },
    // 分页器--当前页
    handleCurrentChange (val) {
      // console.log(`当前页: ${val}`)
      // pagenum 当前页
      this.pagenum = val
      this.getUserList()
    },
    // 搜索功能
    searchUser () {
      this.query = this.inputValue
      this.pagenum = 1
      this.getUserList()
    },
    // 修改用户状态
    async changeState (id, state) {
      try {
        const { meta } = await this.$axios.put(`users/${id}/state/${state}`)
        // const { meta } = res
        console.log(meta)
        if (meta.status === 200) {
          this.$message.success(meta.msg)
        } else {
          this.$message.error(meta.msg)
        }
      } catch (e) {
        console.log(e)
      }
    },
    // 添加对话的显示
    showAddDialog () {
      this.dialogVisible = true
    },
    // 添加用户
    async addUser () {
      // 先进行表单校验 再发送ajax
      try {
        await this.$refs.form.validate()
        // console.log(this.addForm)
        const { meta } = await this.$axios.post(`users`, this.addForm)
        //  const meta = res.meta
        console.log(meta)
        if (meta.status === 201) {
          this.$message.success(meta.msg)
          // 关闭对话框
          this.dialogVisible = false
          // 需要更改页数 添加后的页数是total+1
          this.pagenum = Math.ceil(++this.total / this.pagesize)
          this.getUserList()
        } else {
          this.$message.error(meta.msg)
        }
      } catch (e) {
        console.log(e)
      }
    },
    // 关闭对话框 重置输入框
    closeDialog () {
      this.$refs.form.resetFields()
    },
    // 删除用户
    async deleteUser (id) {
      try {
        await this.$confirm('此操作将永久删除该文件, 是否继续?', '温馨提示', { type: 'warning' })
        // console.log(2)

        const { meta } = await this.$axios.delete(`users/${id}`)
        if (meta.status === 200) {
          console.log(1)

          this.$message.success(meta.msg)
          // 当前页只有一条数据时 如果此页被删除了 当前页码需要-1
          if (this.useList.length === 1 && this.pagenum > 1) {
            this.pagenum--
          }
          this.getUserList()
        }
      } catch (e) {
        console.log(e)
      }
    },
    // 修改对话框显示
    showEditDialog (row) {
      this.editDialogVisible = true
      this.editForm.email = row.email
      this.editForm.username = row.username
      this.editForm.mobile = row.mobile
      this.editForm.id = row.id
    },
    // 修改内容
    async editUser (id) {
      try {
        await this.$refs.editForm.validate()
        const { id, email, mobile } = this.editForm
        const { meta } = await this.$axios.put(`users/${id}`, { email, mobile })
        if (meta.status === 200) {
          this.$message.success(meta.msg)
          // 关闭对话框
          this.editDialogVisible = false
          // 重新渲染
          this.getUserList()
        } else {
          this.$message.error(meta.msg)
        }
      } catch (e) {
        console.log(e)
      }
    },
    // 分配角色对话框显示
    async showAssignDialog (row) {
      this.assignDialogVisible = true
      this.assignForm.id = row.id
      this.assignForm.username = row.username
      // 回显rid
      const res = await this.$axios.get(`users/${row.id}`)
      // console.log(res)
      if (res.meta.status === 200) {
        this.$message.success(res.meta.msg)
        const rid = res.data.rid
        // 对新添加的用户rid是-1
        this.assignForm.rid = rid === -1 ? '' : rid
      } else {
        this.$message.error(res.meta.msg)
      }
      const { meta, data } = await this.$axios.get('roles')
      if (meta.status === 200) {
        this.$message.success(meta.msg)
        // console.log(data)
        this.options = data
      } else {
        this.$message.error(meta.msg)
      }
    },
    // 分配用户角色
    async assginRoles () {
      const { rid, id } = this.assignForm
      const { meta } = await this.$axios.put(`users/${id}/role`, { rid })
      // console.log(res)
      if (meta.status === 200) {
        this.$message.success(meta.msg)
        // 关闭对话框
        this.assignDialogVisible = false
        // 重新渲染
        this.getUserList()
      } else {
        this.$message.error(meta.msg)
      }
    }
  }
}
</script>

<style lang="scss" >
.users {
  .input-with-select {
    width: 300px;
    margin-bottom: 10px;
  }
  .addBtn {
    margin: 0 20px;
  }
}
</style>
